<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="home-content">
      <h1 class="page-title">HousingHub 首页</h1>
          <div class="welcome-section">
<!--            展示用户名-->
            <h2>欢迎回来，{{ currentUser.username || '用户' }}！</h2>
            <p>发现您附近的好房源</p>
          </div>

          <!-- 统计卡片 -->
          <div class="stats-section">
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="stat-card" @click="goToFavorites">
                  <div class="stat-icon bg-blue">
                    <Star />
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ favoriteHouses }}</div>
                    <div class="stat-title">收藏房源</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="stat-card" @click="goToHistory">
                  <div class="stat-icon bg-green">
                    <View />
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ viewedHouses }}</div>
                    <div class="stat-title">浏览记录</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="stat-card" @click="goToNotifications">
                  <div class="stat-icon bg-orange">
                    <Bell />
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ notifications }}</div>
                    <div class="stat-title">系统通知</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="stat-card">
                  <div class="stat-icon bg-red">
                    <House />
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ publishedHouses }}</div>
                    <div class="stat-title">发布房源</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="stat-card">
                  <div class="stat-icon bg-purple">
                    <ChatLineSquare />
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ messages }}</div>
                    <div class="stat-title">消息</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="stat-card">
                  <div class="stat-icon bg-blue">
                    <User />
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ contacts }}</div>
                    <div class="stat-title">联系人</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <!-- 附近房源 -->
          <div class="nearby-houses-section">
            <div class="section-header">
              <h3>附近房源</h3>
              <div class="section-controls">
                <div class="location-display">
                  <el-icon><Location /></el-icon>
                  <span>{{ userLocation ? userLocation.address : '北京市朝阳区' }}</span>
                </div>
                <el-button @click="refreshHouses" :loading="refreshing">刷新</el-button>
              </div>
            </div>

            <div class="houses-container">
              <el-row :gutter="20">
                <el-col
                    :span="8"
                    v-for="house in nearbyHouses"
                    :key="house.id"
                >
                  <div class="house-card" @click="viewHouseDetail(house.id)">
                    <div class="house-image">
                      <img :src="house.image" :alt="house.title" />
                      <div class="house-price">¥{{ house.price }}/月</div>
                    </div>
                    <div class="house-info">
                      <h4 class="house-title">{{ house.title }}</h4>
                      <div class="house-meta">
                        <span>{{ house.area }}㎡</span>
                        <span>{{ house.layout }}</span>
                        <span>{{ house.address }}</span>
                      </div>
                      <div class="house-tags">
                        <el-tag size="small" type="primary">精装</el-tag>
                        <el-tag size="small" type="success">可直租</el-tag>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>

              <!-- 加载更多 -->
              <div class="load-more">
                <el-button @click="loadMoreHouses" :loading="loadingMore">加载更多</el-button>
              </div>
            </div>
          </div>
          </div>
  </UserLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { goToAgentApply as utilGoToAgentApply } from '@/utils/agentUtils'
import { getUserInfo } from '@/utils/auth'
import { getCurrentPosition } from '@/utils/map'
import UserLayout from '@/components/layout/UserLayout.vue'
import {
  Star,
  View,
  Bell,
  Location
} from '@element-plus/icons-vue'

const router = useRouter()
const activeMenu = ref('dashboard')
const activeIndex = ref('1')
const locating = ref(false)
const refreshing = ref(false)
const loadingMore = ref(false)
const userLocation = ref(null)
const nearbyHouses = ref([
  {
    id: 1,
    title: '精致一居室公寓',
    address: '北京市朝阳区CBD建国路123号',
    price: 4500,
    area: 60,
    layout: '1室1厅',
    image: 'https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1769&q=80'
  },
  {
    id: 2,
    title: '豪华两居室',
    address: '北京市朝阳区三里屯太古里456号',
    price: 8500,
    area: 90,
    layout: '2室1厅',
    image: 'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
  },
  {
    id: 3,
    title: '舒适三居室',
    address: '北京市朝阳区国贸SOHO789号',
    price: 12000,
    area: 120,
    layout: '3室2厅',
    image: 'https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
  },
  {
    id: 4,
    title: '温馨单间出租',
    address: '北京市朝阳区双井地铁站101号',
    price: 2800,
    area: 35,
    layout: '单间',
    image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
  },
  {
    id: 5,
    title: '精品复式公寓',
    address: '北京市朝阳区大望路202号',
    price: 7200,
    area: 85,
    layout: '2室1厅',
    image: 'https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1753&q=80'
  },
  {
    id: 6,
    title: '现代化loft公寓',
    address: '北京市朝阳区798艺术区303号',
    price: 6500,
    area: 75,
    layout: '1室1厅',
    image: 'https://images.unsplash.com/photo-1575517114892-6a0eb8c4fd5d?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
  },
  {
    id: 7,
    title: '高端服务式公寓',
    address: '北京市朝阳区三里屯404号',
    price: 12000,
    area: 120,
    layout: '2室1厅',
    image: 'https://images.unsplash.com/photo-1600607687920-4e2a09cf159d?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1769&q=80'
  },
  {
    id: 8,
    title: '市中心精装公寓',
    address: '北京市东城区王府井505号',
    price: 9500,
    area: 70,
    layout: '1室1厅',
    image: 'https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
  },
  {
    id: 9,
    title: '学区房出租',
    address: '北京市海淀区中关村一小附近606号',
    price: 11000,
    area: 100,
    layout: '3室1厅',
    image: 'https://images.unsplash.com/photo-1600566753157-7b40d354b951?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
  }
])

// 统计数据
const favoriteHouses = ref(12)
const viewedHouses = ref(48)
const notifications = ref(3)
const publishedHouses = ref(2)
const messages = ref(5)
const contacts = ref(18)
// 获取当前用户信息
const currentUser = ref({})

// 初始化用户信息
const initUserInfo = () => {
  const userInfo = getUserInfo()
  if (userInfo) {
    currentUser.value = userInfo
  }
}

// 定位用户
const locateUser = async () => {
  locating.value = true
  try {
    const position = await getCurrentPosition()
    userLocation.value = {
      address: position.address,
      lat: position.lat,
      lng: position.lng,
      city: position.city,
      district: position.district
    }
    ElMessage.success('定位成功')
    // 定位成功后刷新附近房源
    await refreshHouses()
  } catch (error) {
    console.error('定位失败:', error)
    ElMessage.warning('定位失败，使用默认位置')
    // 使用默认位置（北京市中心）
    userLocation.value = {
      address: '北京市朝阳区',
      lat: 39.9042,
      lng: 116.4074,
      city: '北京市',
      district: '朝阳区'
    }
  } finally {
    locating.value = false
  }
}

// 刷新房源
const refreshHouses = () => {
  refreshing.value = true
  // 模拟刷新过程
  setTimeout(() => {
    refreshing.value = false
    ElMessage.success('刷新成功')
  }, 1500)
}

// 加载更多房源
const loadMoreHouses = () => {
  loadingMore.value = true
  // 模拟加载更多房源
  setTimeout(() => {
    loadingMore.value = false
    const moreHouses = [
      {
        id: 10,
        title: '海景房出租',
        address: '北京市朝阳区朝阳公园707号',
        price: 15000,
        area: 150,
        layout: '3室2厅',
        image: 'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
      },
      {
        id: 11,
        title: '别墅出租',
        address: '北京市朝阳区别墅区808号',
        price: 25000,
        area: 300,
        layout: '4室3厅',
        image: 'https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
      },
      {
        id: 12,
        title: '经济实惠单间',
        address: '北京市朝阳区传媒大学909号',
        price: 1800,
        area: 25,
        layout: '单间',
        image: 'https://images.unsplash.com/photo-1584622650111-993a426fbf0a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1770&q=80'
      }
    ]

    nearbyHouses.value = [...nearbyHouses.value, ...moreHouses]
    ElMessage.success('加载更多房源成功')
  }, 1500)
}

// 顶部导航栏跳转
const goToHome = () => {
  router.push('/')
}

const goToSearch = () => {
  router.push('/house/search')
}

const goToPublish = () => {
  router.push('/house/publish')
}

const goToMessages = () => {
  router.push('/message')
}

// 用户命令处理
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      ElMessage.success('退出登录成功')
      localStorage.removeItem('userEmail')
      localStorage.removeItem('isLoggedIn')
      router.push('/login')
      break
  }
}

// 侧边栏跳转
const goToPublishNew = () => {
  router.push('/house/publish')
}

const goToMyHouses = () => {
  router.push('/house/my-houses')
}

const goToAgentApply = async () => {
  await utilGoToAgentApply(router)
}

const goToAgentStatus = () => {
  router.push('/agent/status')
}

const goToAgentHouses = () => {
  router.push('/agent/houses')
}

const goToTenant = () => {
  router.push('/rental/tenant')
}

const goToLandlord = () => {
  router.push('/rental/landlord')
}

const goToAgentRental = () => {
  router.push('/rental/agent')
}

const goToProfile = () => {
  router.push('/profile')
}

// 统计卡片跳转
const goToFavorites = () => {
  ElMessage.info('跳转到收藏房源页面')
  // router.push('/favorites')
}

const goToHistory = () => {
  ElMessage.info('跳转到浏览记录页面')
  // router.push('/history')
}

const goToNotifications = () => {
  ElMessage.info('跳转到系统通知页面')
  // router.push('/notifications')
}

// 查看房源详情
const viewHouseDetail = (id) => {
  router.push(`/house/detail/${id}`)
}

// 页面加载时初始化
onMounted(async () => {
  // 初始化用户信息
  initUserInfo()

  // 自动获取用户位置
  try {
    await locateUser()
  } catch (error) {
    console.error('自动定位失败:', error)
    // 使用默认位置
    userLocation.value = {
      address: '北京市朝阳区',
      lat: 39.9042,
      lng: 116.4074,
      city: '北京市',
      district: '朝阳区'
    }
  }
})
</script>

<style scoped>
/* 页面内容样式 */

.home-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  z-index: 1;
  position: relative;
}

.top-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 30px;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.navbar-center {
  flex: 1;
  margin: 0 20px;
}

:deep(.el-menu--horizontal) {
  border: none;
  background: transparent !important;
}

:deep(.el-menu--horizontal .el-menu-item) {
  color: white;
  border: none;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  color: #4A90E2 !important;
  border: none;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.location-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
}

.location-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.location-info {
  color: white;
  font-size: 14px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: white;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  padding: 20px 0;
  height: 100%;
  box-shadow: 3px 0 10px rgba(0, 0, 0, 0.2);
}

.el-menu-vertical {
  border: none !important;
  height: 100%;
}

.el-menu-item,
.el-sub-menu__title {
  margin: 5px 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  overflow-y: auto;
  padding: 20px;
}

.welcome-section {
  margin-bottom: 30px;
}

.welcome-section h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0 0 10px;
}

.welcome-section p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  height: 100px;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.bg-blue {
  background: linear-gradient(135deg, #4A90E2 0%, #64b5f6 100%);
}

.bg-green {
  background: linear-gradient(135deg, #50E3C2 0%, #80deea 100%);
}

.bg-orange {
  background: linear-gradient(135deg, #FFA500 0%, #ffb74d 100%);
}

.bg-red {
  background: linear-gradient(135deg, #FF6B6B 0%, #ff8a80 100%);
}

.bg-purple {
  background: linear-gradient(135deg, #9B59B6 0%, #ba68c8 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  color: #7f8c8d;
}

.nearby-houses-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
  font-weight: 700;
}

.section-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.location-display {
  font-size: 14px;
  color: #7f8c8d;
  display: flex;
  align-items: center;
  gap: 5px;
}

.houses-container {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 transparent;
}

.houses-container::-webkit-scrollbar {
  width: 6px;
}

.houses-container::-webkit-scrollbar-track {
  background: transparent;
}

.houses-container::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.house-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
  margin-bottom: 20px;
}

.house-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.house-image {
  position: relative;
  height: 200px;
}

.house-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.house-card:hover .house-image img {
  transform: scale(1.05);
}

.house-price {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(74, 144, 226, 0.9);
  color: white;
  padding: 5px 10px;
  border-radius: 20px;
  font-weight: 600;
  font-size: 14px;
}

.house-info {
  padding: 15px;
}

.house-title {
  margin: 0 0 10px;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
}

.house-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #7f8c8d;
}

.house-tags {
  display: flex;
  gap: 5px;
}

.load-more {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-bottom: 20px;
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .stats-section .el-row {
    flex-direction: column;
    gap: 15px;
  }

  .stats-section .el-col {
    width: 100%;
  }
}
</style>
